#!/usr/bin/env python

#import the common lib
import telnetlib
import ftplib
import os
from time import gmtime, strftime

#import the private lib
import notify
import ConfigClass
from CommonLib import log


def conn_tel(host_config, action_type, command_list, checkpoint):
    
    TELNET_DEBUG_LEVEL = ConfigClass.SystemConfig().get_telnet_debug_level()
    TELNET_TIMEOUT = ConfigClass.SystemConfig().get_telnet_timeout()
    MODE = ConfigClass.SystemConfig().get_mode()
    
    try:
        
        tn = telnetlib.Telnet(host_config['host'])
        
    except:
        
        #print 'can not open host: ' + host_config['host']
        log('can not open host: ' + host_config['host'])
        return

    tn.set_debuglevel(TELNET_DEBUG_LEVEL)
    
    if(host_config['system'] == 'UNIX'):
        
        line_str = "\n"
        pass_str = 'Password:'
    
    elif(host_config['system'] == 'WIN'):
        
        line_str = "\r\n"
        pass_str = 'password:'
    
    else:
        
        #print 'the system type: ' + host_config['system'] + 'is unknown.'
        log('the system type: ' + host_config['system'] + 'is unknown.')
        return
    
    #login the server
    msg = tn.read_until("login:", TELNET_TIMEOUT)
    log(msg)
    tn.write(host_config['user'] + line_str)
    msg = tn.read_until(pass_str, TELNET_TIMEOUT)
    log(msg)
    tn.write(host_config['passwd'] + line_str)

    #execute the commands
    for command in command_list:
        
        tn.write(command + line_str)
    
    if checkpoint != '': 
        msg = tn.read_until(checkpoint, TELNET_TIMEOUT)
        log(msg)
    
    if(MODE == 1):
        log('action done.')
    elif(MODE == 2):
        notify.info(host_config, action_type)
    
    #logout the server
    tn.write("exit" + line_str)
    
    #show all activities
    return tn.read_all()

def conn_ftp(host_config, action_type, command_list):
    
    local_sep = os.path.sep
    BUFSIZE = ConfigClass.SystemConfig().get_ftp_buffer_size()
    FTP_DEBUG_LEVEL = ConfigClass.SystemConfig().get_ftp_debug_level()
    FTP_DEFAULT_DEBUG_LEVEL = ConfigClass.SystemConfig().get_ftp_default_debug_level()
    
    if host_config['system'] == 'UNIX':
        
        remote_sep = '/'
    
    else:
        
        remote_sep = '\\'
    
    ftp = ftplib.FTP()
    
    ftp.set_debuglevel(FTP_DEBUG_LEVEL)
    
    ftp.connect(host_config['host'], host_config['ftpport'])
    ftp.login(host_config['duser'], host_config['dpasswd'])
    
    #print ftp.getwelcome()
    
    if action_type == 'GLOG':
         
        local_path = 'download' + local_sep + 'logs' + local_sep + host_config['id'] + '_' + strftime("%Y%m%d%H%M%S", gmtime()) + local_sep
    
        #check and make local directory
        if os.path.exists(local_path) == False:
                   
            os.mkdir(local_path)
        
        if host_config['section'] == 'WAS':
            
            remote_path = host_config['home'] + 'profiles' + remote_sep + host_config['name'] + remote_sep + 'logs' + remote_sep + host_config['server'] + remote_sep
            
        elif host_config['section'] == 'APACHE':
            
            remote_path = host_config['home'] + 'logs' + remote_sep 
        
        elif host_config['section'] == 'TOMCAT':
            
            remote_path = host_config['home'] + 'logs' + remote_sep 
            
        else:
            
            print 'the section type: ' + host_config['section'] + ' is unknown.'
              
        ftp.cwd(remote_path)
        
        if host_config['section'] == 'WAS':
            
            log_array = ftp.nlst()
        
        elif host_config['section'] == 'TOMCAT':
            
            log_array = []
            log_array.append('catalina.out')
        
        elif host_config['section'] == 'APACHE':
            
            log_array = []
            log_array.append('access_log')
            log_array.append('error_log')
        
        
        for log in log_array:
            
            filename = local_path + log
            
            file_handler = open(filename, 'wb').write
            
            ftp.retrbinary('RETR ' + remote_path + log, file_handler,BUFSIZE)
    
    elif action_type == 'GCONF':
        
        remote_path = '/tmp/'
        
        local_path  = 'download' + local_sep + 'conf' + local_sep + host_config['id'] + '_' + strftime("%Y%m%d%H%M%S", gmtime()) + local_sep
        
        file_name = 'conf.' + host_config['id'] + '.txt'
        
        if os.path.exists(local_path) == False:
            
            os.mkdir(local_path)
        
        ftp.cwd(remote_path)
        
        file_handler = open(local_path + file_name, 'wb').write
        ftp.retrbinary('RETR ' + remote_path + file_name, file_handler,BUFSIZE)
        
    
    else:
        
        print 'the action type: ' + action_type + ' is unknown.'
    
    notify.info(host_config, action_type)
                 
    ftp.set_debuglevel(FTP_DEFAULT_DEBUG_LEVEL)
    
    ftp.quit() 
    